import Environment, Grid, Nanobot, random, sys, pygame, os #@UnresolvedImport



def readFile(task,grid):
    path = sys.path[0]
    file = open(os.path.join(path, "../tasks/",task))
    contents = file.read()
    lines = contents.split("\n")
    
    for line in lines:
        items = line.split(" ")
        if items[0] == "Nanobot":
            grid.addObj(Nanobot.Nanobot( [int(items[1]), int(items[2])], 10))
        if items[0] == "Goal":
            grid.addObj(Environment.Goal( [int(items[1]), int(items[2])], 10))
    return grid.gridrepr 
    
    
'''
    A GameGrid object tracks the state of all objects in the game space
    and relays this information to the nanobots, as well as controlling
    all GUI information.
'''
class GameGUI():
    pygame.init()
    Clock = pygame.time.Clock()    

    size = width, height = 500, 500
    gridsize = 10
    nanobots = []
    screen = None
    backgroundcolor = (255,255,255)
    velocity = 5                    # Sets movement per iteration in terms of pixels
                                    # This can also be thought of as the step size
    framerate = 1                  # Max FPS
    
    running = True
    nanovision = False
    viewSeen = False
    
    # Constructor for GameGrid, creates blank lists of objects and sprites,
    # and creates the gui screen
    def __init__(self, worldGrid): 
        self.screen = pygame.display.set_mode(self.size)       
        # Creates a discrete representation of the grid based on gridsize
        self.grid = worldGrid
        for obj in self.grid.objects:
            if isinstance(obj, Nanobot.Nanobot):
                self.nanobots.append(obj)
                
    def testStart(self):
        while 1:
            self.Clock.tick(self.framerate)
            self.checkEvents()
            if self.running:
                for bot in self.nanobots:
                    bot.performAction()
                    self.screen.blit(bot.image,bot.rect)
                self.updateScreen(self.screen)

    def checkEvents(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.unicode == " ":
                    self.running = not self.running
                elif event.unicode == "q":
                    sys.exit()
                elif event.unicode == "=":
                    self.framerate = self.framerate+5
                elif event.unicode == "-":
                    self.framerate = self.framerate-5
                elif event.unicode == "d":
                    self.nanovision = not self.nanovision
                elif event.unicode == "v":
                    self.viewSeen = not self.viewSeen
                elif event.unicode == "r":
                    print "NO IDEA HOW TO CONTACT MASTER COMP"
                    
    # Begins the system by starting a loop that will move the bots and
    # update the gui once per timestep
    def begin(self,goals):
        for robot in self.sprites:
            self.screen.blit(robot.image,robot.rect)    
        while 1:
            self.Clock.tick(self.framerate)
            self.checkEvents()
            if self.running:
                self.sprites = self.moveSprites(self.sprites, self.grid.objects, goals)           
            self.updateScreen(self.screen)

    # Updates the gui to reflect the positions of all elements
    def updateScreen(self, screen):
        screen.fill(self.backgroundcolor)
        for obj in self.grid.objects:
            screen.blit(obj.image, obj.rect)
        if self.viewSeen:
            for y in range(0, self.grid.size):
                for x in range(0, self.grid.size):
                    # If there are no objects in this grid
                    if not self.grid.gridrepr[y][x].contents and self.grid.gridrepr[y][x].viewed:
                        image = pygame.Surface([self.gridsize, self.gridsize])
                        image.fill((255, 0, 0))
                        screen.blit(image, (self.gridsize * y, self.gridsize * x))
        for bot in self.nanobots:
            screen.blit(bot.image, bot.rect)
            if self.nanovision:
                image = pygame.Surface([self.gridsize,self.gridsize])
                image.fill((0,255,0))
                screen.blit(image, bot.rect.move(self.gridsize,0))
                screen.blit(image, bot.rect.move(self.gridsize*-1,0))
                screen.blit(image, bot.rect.move(0, self.gridsize))
                screen.blit(image, bot.rect.move(0, self.gridsize*-1))
                screen.blit(image, bot.rect.move(self.gridsize*-1, self.gridsize*-1))
                screen.blit(image, bot.rect.move(self.gridsize, self.gridsize*-1))
                screen.blit(image, bot.rect.move(self.gridsize*-1, self.gridsize))
                screen.blit(image, bot.rect.move(self.gridsize, self.gridsize))
        pygame.display.flip()
        return None
    
    # Moves the sprites/nanobots one step.
    def moveSprites(self, sprites, objects, goals):
        for goal in goals:
            sprite = sprites[goals.index(goal)]
            object = objects[goal]
            if sprite.rect.centerx != object.rect.centerx:
                movex = (-self.velocity*(abs(sprite.rect.centerx-object.rect.centerx) / float(sprite.rect.centerx-object.rect.centerx)))
            else:
                movex = 0
            if sprite.rect.centery != object.rect.centery:
                movey = (-self.velocity*(abs(sprite.rect.centery-object.rect.centery) / float(sprite.rect.centery-object.rect.centery)))
            else:
                movey = 0
            speed = (movex,movey)
            sprite.rect = sprite.rect.move(speed)
            if sprite.rect.left < 0 or sprite.rect.right > self.width or sprite.rect.top < 0 or sprite.rect.bottom > self.height or len(sprite.rect.collidelistall(self.sprites)) > 1:
                speed = map(lambda x: -x, speed)
                sprite.rect=sprite.rect.move(speed)
        return sprites